7.1 How to keep data in client

  1. Motivations
    • Sometimes we need to keep data in our cell phones (or desktop computers), not server. Is it safe?
    • How to keep a bit large data in the client side, especially when the data does not have to be submitted to the server side?

  2. WebStorage
    • Read all in HTML5 Local Storage.
      • Can your web applications store data locally within the client's file system, so that other programs can use the data?
      • Can the data stored in local storage be transferred to server-side scripts like cookies?
      • Can the data stored in local storage be shared by all the programs from the same domain?
      • localStorage.???() is used to set a data item, localStorage.???() is used to get a data item, and localStorage.???() is used to remove a data item.
      • What kind of data can be stored?
      • How do you think of localStorage.test = 'Wow!' and localStorage.setItem('test', 'Wow!')?
      • Name and value pairs are always stored as strings. Can you store an object in localStorage? If so, how?
        localStorage.setItem("T1234567", JSON.stringify({name: "Agent Smith", age: 20}));
        alert(JSON.parse(localStorage.getItem("T1234567")).age);
        
      • What is the life span of the data in localStorage?
      • Do you remember how to delete a property of an object?
        .setItem(), .getItem(), .removeItem()
      • How do you store data within the user's browser for only one session?
      • How can you store server side data in client?
      • Try this memo app. Add some memos, close it, reopen it, and display all the memos.
      • Trial 1: Let's try to make a memo application using the local storage. In this exercise, 'db-demo' is used to keep string values. For testing, you store a memo, reload the page, and display the memo to see if you can.


    • How can you store more complex data, i.e., objects?
      localStorage.setItem("john", JSON.stringify({name: "Smith", age: 20}));
      localStorage.course = "COMP3540";
      alert(JSON.parse(localStorage.getItem("john")).age + "; " + localStorage.course);
      
    • How to browse all the data in localStorage
      for (var p in localStorage)  // localStorage is an object.
          alert(p + ' -> ' + localStorage[p]);
      
    • Can you implement a client-side key-value database? Using localStorage?
    • You may be interested in offline web applications. Visit HTML5 FEATURES OFFLINE.
    • You may be interested in client-side databases, such as IndexedDB. Visit Client-Side Storage.
    • Just a question. How can you store data in the server system?

  3. Learning outcomes
    • Use WebStorage to keep data in the user's browser.